package com.egg.ylt.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.ViewTreeObserver;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.services.core.LatLonPoint;
import com.egg.ylt.R;
import com.egg.ylt.Utils.API;
import com.egg.ylt.Utils.Constants;
import com.egg.ylt.Utils.CustomUtils;
import com.egg.ylt.Utils.GlideImageLoader;
import com.egg.ylt.Utils.MDGridRvDividerDecoration;
import com.egg.ylt.Utils.ShopDetailUtil;
import com.egg.ylt.Utils.SpaceItemDecoration;
import com.egg.ylt.Utils.StatusBarUtil;
import com.egg.ylt.Utils.StringUtil;
import com.egg.ylt.adapter.ADA_HealthAirAdapter;
import com.egg.ylt.adapter.ADA_HealthWaterAdapter;
import com.egg.ylt.adapter.ADA_NewCouponList;
import com.egg.ylt.adapter.ADA_ShopDetailCoupon;
import com.egg.ylt.adapter.ADA_ShopDetailTeacher;
import com.egg.ylt.pojo.CouponEntity;
import com.egg.ylt.pojo.NatatoriumByidEntity;
import com.egg.ylt.pojo.RealtimeDataEntity;
import com.egg.ylt.pojo.ShopDetailCouponEntity;
import com.egg.ylt.pojo.TabEntity;
import com.egg.ylt.presenter.impl.ShopDetailPresenterImpl;
import com.egg.ylt.view.IShopDetailView;
import com.egg.ylt.widget.FlowLayout;
import com.egg.ylt.widget.MyScrollView;
import com.egg.ylt.widget.NewsScrollview;
import com.egg.ylt.widget.browseimg.JBrowseImgActivity;
import com.egg.ylt.widget.browseimg.util.JMatrixUtil;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMWeb;
import com.yonyou.framework.library.base.BaseActivity;
import com.yonyou.framework.library.bean.ErrorBean;
import com.yonyou.framework.library.common.CommonUtils;
import com.yonyou.framework.library.common.utils.ListUtil;
import com.yonyou.framework.library.common.utils.ScreenUtil;
import com.yonyou.framework.library.common.utils.ToastUtil;
import com.yonyou.framework.library.dialog.AlertDialog;
import com.yonyou.framework.library.widgets.tablayout.CommonTabLayout;
import com.yonyou.framework.library.widgets.tablayout.CustomTabEntity;
import com.yonyou.framework.library.widgets.tablayout.OnTabSelectListener;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by lijiateng on 2019/2/23.
 */

public class ACT_ShopDetail extends BaseActivity<ShopDetailPresenterImpl> implements IShopDetailView {

    private static final int MSG_WHAT_UPDATE_AIR_AND_WATER = 0;

    @BindView(R.id.fl_shop_detail)
    FrameLayout flRoot;
    @BindView(R.id.shop_details_banner)
    Banner shopDetailsBanner;
    @BindView(R.id.shop_details_tv_shop_name)
    TextView shopDetailsTvShopName;
    @BindView(R.id.tv_shop_address)
    TextView tvShopAddress;
    @BindView(R.id.tv_distance)
    TextView tvDistance;
    @BindView(R.id.fl_label)
    FlowLayout flLabel;
    @BindView(R.id.shop_detail_scrollview)
    MyScrollView shopDetailScrollview;
    @BindView(R.id.shop_details_iv_back)
    ImageView shopDetailsIvBack;

    @BindView(R.id.shop_details_iv_more)
    ImageView shopDetailsIvMore;
    @BindView(R.id.shop_details_iv_share)
    ImageView shopDetailsIvShare;
    @BindView(R.id.shop_details_iv_collect)
    ImageView shopDetailsIvCollect;
    @BindView(R.id.shop_details_rl_top)
    RelativeLayout shopDetailsRlTop;
    @BindView(R.id.ll_fake_navi)
    LinearLayout llFakeNavi;
    @BindView(R.id.ll_navi)
    LinearLayout llNavi;
    @BindView(R.id.tl_fake_navi)
    CommonTabLayout tlNavi;

    @BindView(R.id.ll_service_list)
    LinearLayout llService;
    @BindView(R.id.ll_show_more_service)
    TextView llShowMoreService;
    @BindView(R.id.ll_more_service)
    LinearLayout llMoreService;
    @BindView(R.id.tv_banner_curr)
    TextView tvBannerCurr;
    @BindView(R.id.tv_banner_total)
    TextView tvBannerTotal;
    @BindView(R.id.tv_check_all)
    TextView tvCheckAll;


    @BindView(R.id.ll_fill_deduct)
    LinearLayout llFillDeductLayout;
    @BindView(R.id.ll_fill_coupon)
    LinearLayout llFill;
    @BindView(R.id.ll_exp)
    LinearLayout llExpLayout;
    @BindView(R.id.ll_exp_coupon)
    LinearLayout llExp;
    @BindView(R.id.rl_coupon)
    RelativeLayout rlCoupon;

    private AlertDialog shareDialog;

    private RecyclerView airRv;
    private RecyclerView waterRv;

    private ADA_HealthAirAdapter mAirAdapter;
    private ADA_HealthWaterAdapter mWaterAdapter;

    private String[] mTitles = {"服务项目", "次卡专区", "商家信息", "游玩须知"};
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private MyOnTabSelectListener myOnTabSelectListener = new MyOnTabSelectListener();

    private boolean isShowNavi = false;
    private boolean isScrollEnable = true;

    private int fakeNaviTop;
    private int naviHeight;
    private int serviceTop;
    private int timesCardTop;
    private int shopDetailTop;
    private int mustKnowTop;

    private String mShopId;

    // 传递到地图界面
    private String shopName;
    private String shopAddress;
    private String mShopPhone;
    private LatLonPoint shopPosition;
    private LatLonPoint myPosition;

    private PopupWindow menuDialog;

    private List<NatatoriumByidEntity.BannerListBean> albumList;
    private ArrayList<String> bannerDisplayList = new ArrayList<>();
    private String mOpenTime;

    private ShopDetailCouponEntity mShopCouponEntity;
    private ADA_ShopDetailCoupon mShopCouponAdapter;
    // add by dlx 用来保持直播链接
    private String videoUrl = "";

    @Override
    public void showBusinessError(ErrorBean error) {

    }

    @Override
    public void showNetError() {
        finish();
    }

    @Override
    protected boolean isApplyKitKatTranslucency() {
        return false;
    }

    @Override
    protected void getBundleExtras(Bundle extras) {

    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.act_shop_details_new_new;
    }

    @Override
    protected View getLoadingTargetView() {
        return shopDetailScrollview;
    }

    @Override
    protected void initViewsAndEvents() {
        StatusBarUtil.setStatusBarColor(this, R.color.ylt_whit);
        StatusBarUtil.StatusBarLightMode(this);
        CustomUtils.setImmersiveStatusBar(this, flRoot);
        initView();
        shopDetailsIvCollect.setOnClickListener(null);
        mShopId = getIntent().getStringExtra("id");
        mPresenter.getShopDetails(mShopId);

    }

    private void initView() {

        // 监听 GlobalLayoutChange
        setViewTreeObserver(findViewById(R.id.type_services));

        setBanner();

        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i]));
        }
        tlNavi.setTabData(mTabEntities);
        tlNavi.setOnTabSelectListener(myOnTabSelectListener);

        shopDetailScrollview.setOnScrollListener(new NewsScrollview.OnScrollListener() {
            @Override
            public void onScroll(int l, int t, int oldl, int oldt) {

                // 控制导航栏显示隐藏
                if (!isShowNavi && t >= fakeNaviTop) {
                    llNavi.setVisibility(View.VISIBLE);
                    isShowNavi = true;
                } else if (isShowNavi && t < fakeNaviTop) {
                    llNavi.setVisibility(View.INVISIBLE);
                    isShowNavi = false;
                }

                // 根据当前 ScrollView 所在位置判断 tabLayout 的位置
                if (isScrollEnable) {
                    if (t >= serviceTop && t < timesCardTop) {
                        tlNavi.setCurrentTab(0);
                    } else if (t >= timesCardTop && t < shopDetailTop) {
                        tlNavi.setCurrentTab(1);
                    } else if (t >= shopDetailTop && t < mustKnowTop) {
                        tlNavi.setCurrentTab(2);
                    } else if (t >= mustKnowTop) {
                        tlNavi.setCurrentTab(3);
                    }
                }

            }
        });

    }

    /**
     * banner轮播图属性设置
     */
    private void setBanner() {
        //设置指示器居中
        shopDetailsBanner.setIndicatorGravity(BannerConfig.CENTER);
        //设置圆形指示器
        shopDetailsBanner.setBannerStyle(BannerConfig.NOT_INDICATOR);
        //设置图片加载器
        shopDetailsBanner.setImageLoader(new GlideImageLoader());
        //设置轮播时间
        shopDetailsBanner.setDelayTime(3000);
        //banner点击事件监听
        shopDetailsBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {

                if (ListUtil.isListEmpty(albumList) || ListUtil.isListEmpty(bannerDisplayList)) {
                    return;
                }

                // 如果是第一张图，则跳转视频播放页
                if (position == 0) {
                    ACT_ShopAlbum.startAc(mContext, ACT_ShopAlbum.TYPE_LIVE, shopName, videoUrl, albumList);
                    return;
                }

                List<Rect> rects = new ArrayList<>();
                for (String s : bannerDisplayList) {
                    rects.add(JMatrixUtil.getDrawableBoundsForBanner(shopDetailsBanner));
                }
                JBrowseImgActivity.start(mContext, bannerDisplayList, position, rects);
            }
        });

        // banner 滑动监听
        shopDetailsBanner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (tvBannerCurr != null) {
                    tvBannerCurr.setText(String.valueOf(position + 1));
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    /**
     * 展示banner数据
     *
     * @param entity
     */
    private void setBannerData(final NatatoriumByidEntity entity) {
        videoUrl = entity.getVedioUrl();
        if (!ListUtil.isListEmpty(entity.getBannerList())) {

            // 图片列表
            albumList = entity.getBannerList();

            // 设置 banner
            tvCheckAll.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 传递banner 数据
                    ACT_ShopAlbum.startAc(mContext, ACT_ShopAlbum.TYPE_ALBUM, shopName, videoUrl, albumList);
                }
            });

            // banner 展示列表
            for (NatatoriumByidEntity.BannerListBean bean : entity.getBannerList()) {

                // 筛选直播图片
                if (ListUtil.isListEmpty(bannerDisplayList)) {
                    for (NatatoriumByidEntity.BannerListBean bannerListBean : entity.getBannerList()) {
                        if (NatatoriumByidEntity.IMAGE_TYPE_LIVE == bannerListBean.getImageType()) {
                            this.bannerDisplayList.add(bean.getImageUrl());
                            break;
                        }
                    }
                }

                // 筛选头图
                if (NatatoriumByidEntity.IMAGE_TYPE_BANNER == bean.getImageType()) {
                    this.bannerDisplayList.add(bean.getImageUrl());
                }
            }

            //设置banner图片集合
            tvBannerTotal.setText(StringUtil.get(bannerDisplayList.size()));
            shopDetailsBanner.setImages(this.bannerDisplayList);
            //banner设置方法全部调用完毕时最后调用
            shopDetailsBanner.start();
        }

    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        return false;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        return null;
    }

    @OnClick({R.id.ll_service, R.id.ll_times_card, R.id.ll_shop_detail, R.id.ll_must_know,
            R.id.ll_address, R.id.iv_phone, R.id.shop_details_iv_share,
            R.id.ll_bottom_phone, R.id.ll_bottom_service, R.id.tv_reserve, R.id.shop_details_iv_more,
            R.id.shop_details_iv_back, R.id.rl_coupon})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.shop_details_iv_back:
                finish();
                break;
            case R.id.ll_service:
                myOnTabSelectListener.onTabSelect(0);
                break;
            case R.id.ll_times_card:
                myOnTabSelectListener.onTabSelect(1);
                break;
            case R.id.ll_shop_detail:
                myOnTabSelectListener.onTabSelect(2);
                break;
            case R.id.ll_must_know:
                myOnTabSelectListener.onTabSelect(3);
                break;
            case R.id.ll_address:
                goShopAddressMap();
                break;
            case R.id.iv_phone:
            case R.id.ll_bottom_phone:
                CustomUtils.setCallPhoneDialog(this, mShopPhone);
                break;

            case R.id.ll_bottom_service:
                readyGo(ACT_CallCenter.class);
                break;

            case R.id.shop_details_iv_share:
                umShareDialogShow();
                break;

            case R.id.tv_reserve:
                //跳转到预约界面
                if (StringUtil.isEmpty(Constants.TOKEN)) {
                    readyGo(ACT_UserLogin.class);
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putString("shopId", mShopId);
                    bundle.putString("storePhone", mShopPhone);
                    readyGo(ACT_ShopAppointment.class, bundle);
                }
                break;
            case R.id.shop_details_iv_more:
                initMenuDialog();
                menuDialog.showAsDropDown(shopDetailsIvMore, 0, 20);
                break;

            case R.id.rl_coupon:
                showCouponDialog();
                break;

        }
    }

    private void showCouponDialog() {

        if (mShopCouponEntity != null) {

            ArrayList<CouponEntity.ListEntity> couponList = new ArrayList<>();
            couponList.addAll(mShopCouponEntity.getComponTicket());
            couponList.addAll(mShopCouponEntity.getExperienceTicket());

            final com.yonyou.framework.library.dialog.AlertDialog couponDialog
                    = new com.yonyou.framework.library.dialog.AlertDialog.Builder(mContext)
                    .setContentView(R.layout.dialog_coupon_list)
                    .fromBottom(true)
                    .fullWidth()
                    .create();
            couponDialog.setOnClickListener(R.id.tv_close, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    couponDialog.dismiss();
                }
            });

            RecyclerView rvCoupon = couponDialog.getView(R.id.xRecyclerView);
            LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
            layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            rvCoupon.setLayoutManager(layoutManager);
            mShopCouponAdapter = new ADA_ShopDetailCoupon(mContext);
            rvCoupon.setAdapter(mShopCouponAdapter);
            mShopCouponAdapter.update(couponList, true);

            mShopCouponAdapter.setOnButtonClickListener(new ADA_ShopDetailCoupon.OnButtonClickListener() {
                @Override
                public void onClick(CouponEntity.ListEntity model, int position) {
                    mPresenter.requestObtainCoupon(model, position);
                }
            });

            couponDialog.show();
        }


    }

    private void goShopAddressMap() {
        Intent intent = new Intent(this, ACT_ShopPositionMapView.class);
        intent.putExtra("shopAddress", shopAddress);
        intent.putExtra("shopLat", shopPosition.getLatitude());
        intent.putExtra("shopLng", shopPosition.getLongitude());
        intent.putExtra("shopName", shopName);
        if (myPosition != null) {
            intent.putExtra("myLat", myPosition.getLatitude());
            intent.putExtra("myLng", myPosition.getLongitude());
        }
        readyGo(intent);
    }

    private PopupWindow initMenuDialog() {

        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_shop_detail_menu, null);
        menuDialog = new PopupWindow(mContext);
        menuDialog.setContentView(view);
        menuDialog.setWidth(ScreenUtil.dip2px(mContext, 100));
        menuDialog.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        menuDialog.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.color_FFFFFF)));
        menuDialog.setOutsideTouchable(true);

        TextView tvMyOrder = view.findViewById(R.id.tv_my_order);
        tvMyOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                readyGo(ACT_Order.class);
                menuDialog.dismiss();
            }
        });

        TextView tvMyCollect = view.findViewById(R.id.tv_my_collect);
        tvMyCollect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                readyGo(ACT_CollectCentre.class);
                menuDialog.dismiss();
            }
        });

        TextView tvGoBackHome = view.findViewById(R.id.tv_go_back_home);
        tvGoBackHome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                menuDialog.dismiss();
            }
        });

        return menuDialog;

    }

    private void smoothScroll(int typeId) {

        switch (typeId) {
            case R.id.type_services:
                tlNavi.setCurrentTab(0);
                break;
            case R.id.type_times_card:
                tlNavi.setCurrentTab(1);
                break;
            case R.id.type_shop_detail:
                tlNavi.setCurrentTab(2);
                break;
            case R.id.type_must_know:
                tlNavi.setCurrentTab(3);
                break;
        }

        final LinearLayout llService = flRoot.findViewById(typeId);
        int measuredPosition = llService.getTop();

        shopDetailScrollview.scrollTo(0, measuredPosition - naviHeight);

    }

    private int getLayoutTop(int resId) {
        return flRoot.findViewById(resId).getTop() - naviHeight;
    }

    @Override
    public void getShopDetail(NatatoriumByidEntity result) {

        //店铺营业时间
        mOpenTime = result.getOpenTime();

        // 获取店铺位置信息
        shopName = result.getName();
        mShopPhone = result.getLinkPhone();
        shopAddress = result.getAddress();
        shopPosition = new LatLonPoint(result.getLatitude(), result.getLongitude());

        // 店铺是否被收藏
        shopDetailsIvCollect.setSelected(!"0".equals(result.getGetCollect()));
        shopDetailsIvCollect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (StringUtil.isEmpty(Constants.TOKEN)) {
                    readyGo(ACT_UserLogin.class);
                    return;
                }
                if (shopDetailsIvCollect.isSelected()) {
                    mPresenter.setCancelMessage(Constants.TOKEN, mShopId);
                } else {
                    mPresenter.setCollectMessage(Constants.TOKEN, mShopId, Constants.COMPANYID);
                }
            }
        });


        // banner
        setBannerData(result);

        // 店铺名称
        shopDetailsTvShopName.setText(result.getName());
        setShopLabels(result.getLabelList());

        // 地址
        tvShopAddress.setText(result.getAddress());
        tvDistance.setText(result.getDistance());

        // 商家服务
        setServiceData(result.getServerList());

        // 次卡专区
        setTimesCardData(result.getCardList());

        // 人员信息
        setShopServers(result.getTeacherList());

        // 请求空气和水质信息
        setAirAndWaterData(result.getIntroduction());

        // 项目介绍
        setProjectData(result.getProjectList());

    }

    private void setShopLabels(List<String> labelList) {
        if (ListUtil.isListEmpty(labelList)) {
            flLabel.setVisibility(View.GONE);
        } else {
            flLabel.setVisibility(View.VISIBLE);
            for (String label : labelList) {
                flLabel.addView(buildLabel(label));
            }
        }
    }

    /**
     * 店铺项目
     *
     * @param projectList
     */
    private void setProjectData(List<NatatoriumByidEntity.ProjectListBean> projectList) {

        LinearLayout llProjectRoot = findViewById(R.id.ll_project_root);

        // 空页面
        if (ListUtil.isListEmpty(projectList)) {
            llProjectRoot.removeAllViews();
            llProjectRoot.addView(ShopDetailUtil.inflateEmptyLayout(mContext, ShopDetailUtil.TYPE_PROJECT));
            return;
        }

        LinearLayout llProject = llProjectRoot.findViewById(R.id.ll_project);
        final TextView llShowMore = llProjectRoot.findViewById(R.id.ll_show_more_project);
        llShowMore.setVisibility(projectList.size() > 2 ? View.VISIBLE : View.GONE);
        final LinearLayout llMoreProject = llProjectRoot.findViewById(R.id.ll_more_project);
        llShowMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                llShowMore.setVisibility(View.GONE);
                llMoreProject.setVisibility(View.VISIBLE);
            }
        });

        for (int i = 0; i < projectList.size(); i++) {
            if (i <= 1) {
                View view = ShopDetailUtil.inflateProjectItem(mContext, projectList.get(i));
                llProject.addView(view);
            } else {
                View view = ShopDetailUtil.inflateProjectItem(mContext, projectList.get(i));
                llMoreProject.addView(view);
            }
        }

    }

    private void setAirAndWaterData(String introduction) {
        LinearLayout llShopDetail = findViewById(R.id.type_shop_detail);

        // 介绍
        if (!TextUtils.isEmpty(introduction)) {
            TextView tvIntroduce = llShopDetail.findViewById(R.id.tv_introduce);
            tvIntroduce.setText(introduction);
        }

        airRv = llShopDetail.findViewById(R.id.rv_air);
        //空气 设置布局管理器
        GridLayoutManager airManager = new GridLayoutManager(mContext, 2) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        airRv.setLayoutManager(airManager);
        airRv.addItemDecoration(new MDGridRvDividerDecoration(mContext));
        mAirAdapter = new ADA_HealthAirAdapter(mContext);
        airRv.setAdapter(mAirAdapter);
        mAirAdapter.setOnItemClickListener(new ADA_HealthAirAdapter.OnItemClickListener() {
            @Override
            public void onItemClicked(int feature) {
                ACT_WaterAirDetail.startAct(mContext, mShopId, ACT_WaterAirDetail.TYPE_AIR, feature);
            }
        });

        //水质   设置布局管理器
        waterRv = llShopDetail.findViewById(R.id.rv_water);
        GridLayoutManager waterManager = new GridLayoutManager(mContext, 2) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        waterRv.setLayoutManager(waterManager);
        waterRv.addItemDecoration(new MDGridRvDividerDecoration(mContext));
        mWaterAdapter = new ADA_HealthWaterAdapter(mContext);
        waterRv.setAdapter(mWaterAdapter);
        mWaterAdapter.setOnItemClickListener(new ADA_HealthAirAdapter.OnItemClickListener() {
            @Override
            public void onItemClicked(int feature) {
                ACT_WaterAirDetail.startAct(mContext, mShopId, ACT_WaterAirDetail.TYPE_WATER, feature);
            }
        });

        // 获取空气和水质信息
        mPresenter.updateAirAndWaterQuality();

    }

    /**
     * 人员信息
     *
     * @param teacherList
     */
    private void setShopServers(List<NatatoriumByidEntity.TeacherListBean> teacherList) {
        ADA_ShopDetailTeacher teacherAdapter = new ADA_ShopDetailTeacher(mContext);
        LinearLayout llShopDetail = findViewById(R.id.type_shop_detail);
        RecyclerView rvServer = llShopDetail.findViewById(R.id.rv_server);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false);
        rvServer.setLayoutManager(layoutManager);
        rvServer.setAdapter(teacherAdapter);
        teacherAdapter.update(teacherList, true);
    }

    /**
     * 服务信息
     *
     * @param serverList
     */
    private void setServiceData(List<NatatoriumByidEntity.ServerListBean> serverList) {

        // 空页面
        if (ListUtil.isListEmpty(serverList)) {
            LinearLayout llService = findViewById(R.id.type_services);
            llService.removeAllViews();
            llService.addView(ShopDetailUtil.inflateEmptyLayout(mContext, ShopDetailUtil.TYPE_SERVICE));
            return;
        }

        // 超过 3 条数据时才显示「查看更多」
        llShowMoreService.setVisibility(serverList.size() > 3 ? View.VISIBLE : View.GONE);
        llShowMoreService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                llShowMoreService.setVisibility(View.GONE);
                llMoreService.setVisibility(View.VISIBLE);
            }
        });

        for (int i = 0; i < serverList.size(); i++) {
            if (i <= 2) {
                View view = ShopDetailUtil.inflateServiceItem(mContext, serverList.get(i), mShopId, mShopPhone);
                llService.addView(view);
            } else {
                View view = ShopDetailUtil.inflateServiceItem(mContext, serverList.get(i), mShopId, mShopPhone);
                llMoreService.addView(view);
            }
        }
    }

    private TextView buildLabel(String text) {
        TextView textView = new TextView(this);
        textView.setText(text);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
        textView.setPadding(ScreenUtil.dip2px(mContext, 5), ScreenUtil.dip2px(mContext, 2),
                ScreenUtil.dip2px(mContext, 5), ScreenUtil.dip2px(mContext, 2));
        textView.setBackgroundResource(R.drawable.label_bg);
        return textView;
    }

    /**
     * 次卡专区
     *
     * @param cardList
     */
    private void setTimesCardData(List<NatatoriumByidEntity.CardListBean> cardList) {

        LinearLayout llLayout = findViewById(R.id.type_times_card);

        // 空页面
        if (ListUtil.isListEmpty(cardList)) {
            LinearLayout cardRoot = llLayout.findViewById(R.id.ll_card_root);
            cardRoot.removeAllViews();
            cardRoot.addView(ShopDetailUtil.inflateEmptyLayout(mContext, ShopDetailUtil.TYPE_CARD));
            return;
        }

        LinearLayout llTimesCard = llLayout.findViewById(R.id.ll_times_card);
        final LinearLayout llMoreCard = llLayout.findViewById(R.id.ll_more_card);
        final TextView llShowMore = llLayout.findViewById(R.id.ll_show_more_card);

        // 超过 3 条数据时才显示「查看更多」
        llShowMore.setVisibility(cardList.size() > 3 ? View.VISIBLE : View.GONE);
        llShowMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                llShowMore.setVisibility(View.GONE);
                llMoreCard.setVisibility(View.VISIBLE);
            }
        });

        for (int i = 0; i < cardList.size(); i++) {
            if (i <= 2) {
                View view = ShopDetailUtil.inflateTimesCardItem(mContext, cardList.get(i), mOpenTime);
                llTimesCard.addView(view);
            } else {
                View view = ShopDetailUtil.inflateTimesCardItem(mContext, cardList.get(i), mOpenTime);
                llMoreCard.addView(view);
            }
        }

    }


    @Override
    public void delayInflateViews() {

        // 次卡
        ViewStub timeCardStub = findViewById(R.id.stub_times_card);
        timeCardStub.inflate();

        // 门店详情
        ViewStub shopDetailStub = findViewById(R.id.stub_shop_detail);
        shopDetailStub.inflate();

        // 游玩须知
        ViewStub mustKnowStub = findViewById(R.id.stub_must_know);
        final LinearLayout llMustKnow = (LinearLayout) mustKnowStub.inflate();
        WebView webView = llMustKnow.findViewById(R.id.wv_must_know);
        webView.setWebChromeClient(new WebChromeClient());
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setSupportMultipleWindows(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                view.loadUrl(API.BASE_WEB_URL + "/?id=" + mShopId + "#/playNotice");
                return false;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

                ViewGroup.LayoutParams layoutParams = llMustKnow.getLayoutParams();
                layoutParams.height = ScreenUtil.getScreenHeight(mContext);
                llMustKnow.setLayoutParams(layoutParams);

            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }
        });
        webView.loadUrl(API.BASE_WEB_URL + "/?id=" + mShopId + "#/playNotice");

        // 附近商家
//        ViewStub nearByStub = findViewById(R.id.stub_nearby_shop);
//        nearByStub.inflate();

    }

    @Override
    public void updateAirWaterStatus(RealtimeDataEntity result) {
        List<RealtimeDataEntity.AirBean> airList = result.getAir();
        List<RealtimeDataEntity.WaterBean> waterList = result.getWater();

        mAirAdapter.setDataList(airList);
        mWaterAdapter.setDataList(waterList);

        mHandler.sendEmptyMessageDelayed(MSG_WHAT_UPDATE_AIR_AND_WATER, 1000);

    }

    @Override
    public void onCollectedChanged(boolean isCollect) {
        shopDetailsIvCollect.setSelected(isCollect);
    }

    @Override
    public void updateCouponList(ShopDetailCouponEntity result) {

        List<CouponEntity.ListEntity> commomList = result.getComponTicket();
        List<CouponEntity.ListEntity> expList = result.getExperienceTicket();

        if (ListUtil.isListEmpty(commomList) && ListUtil.isListEmpty(expList)) {
            rlCoupon.setVisibility(View.GONE);
        } else {
            mShopCouponEntity = result;
            rlCoupon.setVisibility(View.VISIBLE);
        }

        if (!ListUtil.isListEmpty(commomList)) {
            llFillDeductLayout.setVisibility(View.VISIBLE);
//            for (int i = 0; i < (commomList.size() == 1 ? 1 : 2); i++) {
//                llFill.addView(buildCouponString(commomList.get(i).getTicketName()));
//            }
            for (int i = 0; i < 1; i++) {
                llFill.addView(buildCouponString(commomList.get(i).getTicketName()));
            }
        }

        if (!ListUtil.isListEmpty(expList)) {
            llExpLayout.setVisibility(View.VISIBLE);

//            for (int i = 0; i < (expList.size() == 1 ? 1 : 2); i++) {
//                llExp.addView(buildCouponString(expList.get(i).getTicketName()));
//            }
            for (int i = 0; i < 1; i++) {
                llExp.addView(buildCouponString(expList.get(i).getTicketName()));
            }
        }

    }

    @Override
    public void updateAfterCouponStatusChanged(int position) {
        if (mShopCouponAdapter != null) {
            mShopCouponAdapter.getDataList().get(position).setStatus("0");
            mShopCouponAdapter.notifyDataSetChanged();
        }
    }

    public TextView buildCouponString(String couponName) {
        TextView coupon = new TextView(mContext);
        coupon.setText(couponName);
        coupon.setTextColor(Color.parseColor("#F8B500"));
        coupon.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
        coupon.setPadding(0, ScreenUtil.dip2px(mContext, 5), 0, ScreenUtil.dip2px(mContext, 5));
        coupon.setGravity(Gravity.CENTER);
        coupon.setBackgroundResource(R.drawable.bg_border);

        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(-2, -2);
        layoutParams.setMargins(20, 0, 20, 0);
        coupon.setLayoutParams(layoutParams);
        return coupon;
    }

    @Override
    protected void handleMsg(Message msg) {
        switch (msg.what) {
            case MSG_WHAT_UPDATE_AIR_AND_WATER:
//                mPresenter.updateAirAndWaterQuality();
                break;
        }
    }


    /**
     * 监听 GlobalLayoutChange ，获取各个 View 的 top 值
     *
     * @param view
     */
    private void setViewTreeObserver(View view) {
        view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                naviHeight = llNavi.getMeasuredHeight();
                fakeNaviTop = llFakeNavi.getTop();

                serviceTop = getLayoutTop(R.id.type_services);
                timesCardTop = getLayoutTop(R.id.type_times_card);
                shopDetailTop = getLayoutTop(R.id.type_shop_detail);
                mustKnowTop = getLayoutTop(R.id.type_must_know);
            }
        });
    }

    class MyOnTabSelectListener implements OnTabSelectListener {

        @Override
        public void onTabSelect(int position) {
            switch (position) {
                case 0:
                    smoothScroll(R.id.type_services);
                    break;
                case 1:
                    smoothScroll(R.id.type_times_card);
                    break;
                case 2:
                    smoothScroll(R.id.type_shop_detail);
                    break;
                case 3:
                    smoothScroll(R.id.type_must_know);
                    break;
            }
        }

        @Override
        public void onTabReselect(int position) {

        }
    }


    /**
     * 分享的dialog展示
     */
    public void umShareDialogShow() {
        //判断不为空直接关闭
        if (shareDialog != null) {
            shareDialog.dismiss();
        }
        //友盟分享链接的对象
        String uri = API.SHARE_SHOP_URI + "?id=" + mShopId + "&companyId=" + Constants.COMPANYID;
        final UMWeb web = new UMWeb(uri);
        web.setTitle("分享");
        web.setDescription(" ");
        shareDialog = new AlertDialog.Builder(mContext)
                .setContentView(R.layout.dialog_um_share_view)
                .setCancelableOntheOutside(true)
                .setWidthAndHeight(mScreenWidth, 900)
                .fromBottom(true)
                .create();
        //设置点击事件
        //微信好友
        shareDialog.setOnClickListener(R.id.btn_share_wx, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isInstallByread("com.tencent.mm")) {
                    new ShareAction(mContext)
                            .setPlatform(SHARE_MEDIA.WEIXIN)//传入平台
                            .withMedia(web)//分享链接
                            .setCallback(shareListener)//回调监听器
                            .share();
                } else {
                    ToastUtil.makeText(mContext, "微信未安装", false);
                }
            }
        });
        //QQ空间
        shareDialog.setOnClickListener(R.id.btn_share_qq_space, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (isInstallByread("com.tencent.mobileqq")) {
                    new ShareAction(mContext)
                            .setPlatform(SHARE_MEDIA.QZONE)//传入平台
                            .withMedia(web)//分享链接
                            .setCallback(shareListener)//回调监听器
                            .share();
                } else {
                    ToastUtil.makeText(mContext, "QQ应用未安装", false);
                }
            }
        });
        //新浪微博
        shareDialog.setOnClickListener(R.id.btn_share_sina, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new ShareAction(mContext)
                        .setPlatform(SHARE_MEDIA.SINA)//传入平台
                        .withMedia(web)//分享链接
                        .setCallback(shareListener)//回调监听器
                        .share();
            }
        });
        //QQ好友
        shareDialog.setOnClickListener(R.id.btn_share_qq_friend, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isInstallByread("com.tencent.mobileqq")) {
                    new ShareAction(mContext)
                            .setPlatform(SHARE_MEDIA.QQ)//传入平台
                            .withMedia(web)//分享链接
                            .setCallback(shareListener)//回调监听器
                            .share();
                } else {
                    ToastUtil.makeText(mContext, "QQ应用未安装", false);
                }
            }
        });
        //微信朋友圈
        shareDialog.setOnClickListener(R.id.btn_share_circle, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isInstallByread("com.tencent.mm")) {
                    new ShareAction(mContext)
                            .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)//传入平台
                            .withMedia(web)//分享链接
                            .setCallback(shareListener)//回调监听器
                            .share();
                } else {
                    ToastUtil.makeText(mContext, "微信未安装", false);
                }
            }
        });
        //取消dialog
        shareDialog.setOnClickListener(R.id.btn_share_cancel, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (shareDialog != null) {
                    shareDialog.dismiss();
                }
            }
        });
        //展示
        shareDialog.show();

    }

    private UMShareListener shareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            Toast.makeText(mContext, "分享成功", Toast.LENGTH_LONG).show();
            //判断不为空直接关闭
            if (shareDialog != null) {
                shareDialog.dismiss();
            }
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(mContext, "分享失败" + t.getMessage(), Toast.LENGTH_LONG).show();
            //判断不为空直接关闭
            if (shareDialog != null) {
                shareDialog.dismiss();
            }
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            if (platform.getName().equals("QQ")) {

            } else {
                Toast.makeText(mContext, "取消分享", Toast.LENGTH_LONG).show();
            }
            //判断不为空直接关闭
            if (shareDialog != null) {
                shareDialog.dismiss();
            }

        }
    };

    /**
     * 判断是否安装目标应用
     *
     * @param packageName 目标应用安装后的包名
     * @return 是否已安装目标应用
     */
    private boolean isInstallByread(String packageName) {
        return new File("/data/data/" + packageName).exists();
    }

    @Override
    protected void onPause() {
        super.onPause();

        // 移除 msg 信息
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // 取消 GlobalLayout 的监听
        View viewById = findViewById(R.id.type_services);
        if (viewById != null) {
            viewById.getViewTreeObserver().addOnGlobalLayoutListener(null);
        }

    }
}
